package xgz.service;

import java.io.File;

import com.xgz.model.MP3Info;
import com.xgz.mp3player.AppConstant;
import com.xgz.mp3player.PlayerActivity;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;

public class PlayerService extends Service {

	private MediaPlayer mediaPlayer;
	private boolean isPlaying = false;
	private boolean isPause = false; 
	private boolean isReleased = false;
	private MP3Info mp3Info;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@SuppressLint("NewApi")
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		MP3Info mp3Info = (MP3Info) intent.getSerializableExtra("mp3Info");
		int MSG = intent.getIntExtra("MSG", 1);
	
		switch(MSG){
		case AppConstant.PlayMSG.PLAY_MSG:
			play(mp3Info);break;
		case AppConstant.PlayMSG.PAUSE_MSG:
			pause();break;
		case AppConstant.PlayMSG.STOP_MSG:
			stop();break;
		}
	
		
		
		return super.onStartCommand(intent, flags, startId);
	}

	private String getMp3Path(MP3Info mp3Info){
		String SDCardRoot = Environment.getExternalStorageDirectory()
				.getAbsolutePath()+File.separator;
		String path = SDCardRoot+"mp3"+File.separator+mp3Info.getMp3name();
		return path;
		
	}
	
	private void play(MP3Info mp3Info){
		if(!isPlaying && !isPause){
			String path = getMp3Path(mp3Info);
			mediaPlayer = MediaPlayer.create(PlayerService.this, Uri.parse("file://"+path));
			mediaPlayer.setLooping(false);
			mediaPlayer.start();
			isPause = false;
			isPlaying = true;
			isReleased = false;
		}  else if(mediaPlayer != null ){
			if(!isReleased){
				if(isPause){
					isPause = false;
					isPlaying = true;
					mediaPlayer.start();
				}
			}
			
			
		}
	}
	
	private void pause(){
		if(mediaPlayer != null ){
			if(!isReleased){
				if(!isPause){
					mediaPlayer.pause();
					isPause = true;
					isPlaying = false;
				} else{
					isPause = false;
					isPlaying = true;
					mediaPlayer.start();
				}
			}
		}
	}
	
	private void stop(){
		if(mediaPlayer != null ){
			if(isPlaying||isPause){
				if(!isReleased){
					mediaPlayer.stop();
					mediaPlayer.release();
					isPlaying = false;
					isPause = false;
					isReleased = true;
				}
			}
		}
	}
}
